from odoo import fields, models, api, _
from odoo.exceptions import ValidationError


class HostelRoom(models.Model):

    _name = "hostel.room"
    _description = "Hostel Room Information"
    _rec_name = "room_no"
    _inherit = ['mail.thread', 'mail.activity.mixin']

    name = fields.Char(string="Room Name", required=True)
    room_no = fields.Char("Room No.", required=True)
    floor_no = fields.Integer("Floor No.", default=1, help="Floor Number")
    currency_id = fields.Many2one('res.currency', string='Currency')
    rent_amount = fields.Monetary('Rent Amount', help="Enter rent amount per month")
    hostel_id = fields.Many2one('hostel.hostel', string='Hostel')
    
    # 宿舍设施字段
    amenities_ids = fields.Many2many('hostel.amenities', 'hostel_room_amenities_rel', 
                                   'room_id', 'amenity_id', string="Amenities")
    
    # 学生关联
    student_ids = fields.One2many('hostel.student', 'room_id', string="Students")
    student_count = fields.Integer(string="Student Count", compute='_compute_student_count', store=True)
    
    # 新增字段
    student_per_room = fields.Integer(string="Students per Room", default=1, required=True, 
                                    help="Maximum number of students that can stay in this room")
    availability = fields.Integer(string="Availability", compute='_compute_availability', store=True,
                                help="Number of available beds in this room")
    
    # 房间状态字段
    state = fields.Selection([
        ('unavailable', 'Unavailable'),
        ('available', 'Available'),
        ('closed', 'Closed')
    ], string="Room State", default='unavailable', required=True, 
       help="Current state of the room")
    
    @api.depends('student_ids')
    def _compute_student_count(self):
        for record in self:
            record.student_count = len(record.student_ids)
    
    @api.depends('student_per_room', 'student_count')
    def _compute_availability(self):
        for record in self:
            record.availability = record.student_per_room - record.student_count
    
    # 约束
    _sql_constraints = [
        ('room_no_unique', 'UNIQUE(room_no)', 'Room number must be unique!'),
    ]
    
    @api.constrains('rent_amount')
    def _check_rent_amount(self):
        for record in self:
            if record.rent_amount < 0:
                raise ValidationError(_('Rent amount cannot be negative!'))
    
    @api.constrains('student_per_room')
    def _check_student_per_room(self):
        for record in self:
            if record.student_per_room <= 0:
                raise ValidationError(_('Students per room must be greater than 0!'))
    
    # 状态转换方法
    def can_change_state_to(self, new_state):
        """判断是否可以转换到指定状态"""
        state_transitions = {
            'unavailable': ['available'],
            'available': ['closed'],
            'closed': ['unavailable']
        }
        return new_state in state_transitions.get(self.state, [])
    
    def change_state_to(self, new_state):
        """改变房间状态"""
        if not self.can_change_state_to(new_state):
            raise ValidationError(_('Cannot change state from %s to %s') % (self.state, new_state))
        self.state = new_state
        return True
    
    def set_available(self):
        """将房间状态改为available"""
        return self.change_state_to('available')
    
    def set_closed(self):
        """将房间状态改为closed"""
        return self.change_state_to('closed')
    
    def get_hostel_book_data(self):
        """获取hostel_book模型数据并打印"""
        hostel_books = self.env['hostel.book'].search([])
        print("=== Hostel Book Data ===")
        for book in hostel_books:
            print(f"ID: {book.id}")
            print(f"Partner: {book.partner_id.name if book.partner_id else 'N/A'}")
            print(f"Is Hostel Rector: {book.is_hostel_rector}")
            print(f"Assigned Rooms Count: {book.count_assign_room}")
            print(f"Assigned Rooms: {[room.name for room in book.assign_room_ids]}")
            print("-" * 30)
        print(f"Total Hostel Books: {len(hostel_books)}")
        return hostel_books
    
    def remove_room_members(self):
        """移除房间成员"""
        if not self.student_ids:
            raise ValidationError(_('No students to remove from this room'))
        
        # 使用with_context调用student模型的remove_from_room方法
        for student in self.student_ids:
            student.with_context(from_room=True).remove_from_room()
        
        return {
            'type': 'ir.actions.client',
            'tag': 'reload',
        }
    
    # optional attribute: currency_field='currency_id' incase currency field have another name then 'currency_id'